<template>
  <a-card :bordered="false" class="card-area">
    <!-- 查询区域 -->
    <div>
      <a-form layout="inline" @keyup.enter.native="search">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="标题">
              <a-input
                placeholder="请输入标题"
                v-model="queryParams.title"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <span
              style="float: left;overflow: hidden;"
              class="table-page-search-submitButtons"
            >
              <a-button type="primary" @click="search" icon="search"
                >查询</a-button
              >
              <a-button
                type="primary"
                @click="reset"
                icon="reload"
                style="margin-left: 8px"
                >重置</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="TableInfo"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        }"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a v-if="record.sendStatus === '0'" @click="handleEdit(record)"
            >编辑</a
          >

          <a-divider type="vertical" v-if="record.sendStatus === '0'" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.sendStatus !== '1'">
                <a-popconfirm
                  title="确定删除吗?"
                  @confirm="() => handleDelete(record.id)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="record.sendStatus === '0'">
                <a-popconfirm
                  title="确定发布吗?"
                  @confirm="() => doPublish(record.id)"
                >
                  <a>发布</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="record.sendStatus === '1'">
                <a-popconfirm
                  title="确定撤销吗?"
                  @confirm="() => doRevoke(record.id)"
                >
                  <a>撤销</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleDetail(record)">查看</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <noticeAdd-modal ref="modalForm" @ok="modalFormOk"></noticeAdd-modal>
  </a-card>
</template>

<script>
import NoticeAddModal from "./NoticeAddModal";

export default {
  name: "Notice",
  components: {
    NoticeAddModal
  },
  data() {
    return {
      description: "系统通告表管理页面",
      // 查询条件
      queryParams: {},
      dataSource: [],
      selectedRowKeys: [],
      paginationInfo: null,
      pagination: {
        pageSizeOptions: ["10", "20", "30", "40", "100"],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      url: {
        list: "/api/notice/list",
        delete: "/api/notice/",
        publish: "/api/notice/publish",
        revoke: "/api/notice/revoke"
      }
    };
  },
  computed: {
    columns() {
      return [
        {
          title: "#",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function(t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: "标题",
          align: "center",
          dataIndex: "title"
        },
        {
          title: "发布人",
          align: "center",
          dataIndex: "sender"
        },
        {
          title: "优先级",
          align: "center",
          dataIndex: "priority",
          customRender: function(text) {
            if (text === "L") {
              return <a-tag color="blue"> 低 </a-tag>;
            } else if (text === "M") {
              return <a-tag color="orange"> 中 </a-tag>;
            } else if (text === "H") {
              return <a-tag color="red"> 高 </a-tag>;
            } else {
              return text;
            }
          }
        },
        {
          title: "通告对象",
          align: "center",
          dataIndex: "msgType",
          customRender: function(text) {
            if (text === "USER") {
              return "指定用户";
            } else if (text === "ALL") {
              return "全体用户";
            } else {
              return text;
            }
          }
        },
        {
          title: "发布状态",
          align: "center",
          dataIndex: "sendStatus",
          customRender: function(text) {
            if (text === "0") {
              return <a-tag color="blue"> 未发布 </a-tag>;
            } else if (text === "1") {
              return <a-tag color="green"> 已发布 </a-tag>;
            } else if (text === "2") {
              return <a-tag color="red"> 已撤销 </a-tag>;
            } else {
              return text;
            }
          }
        },
        {
          title: "发布时间",
          align: "center",
          dataIndex: "sendTime"
        },
        {
          title: "撤销时间",
          align: "center",
          dataIndex: "cancelTime"
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" }
        }
      ];
    }
  },
  mounted() {
    this.fetch();
  },
  methods: {
    fetch(params = {}) {
      // 显示loading
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize;
        params.pageNum = this.pagination.defaultCurrent;
      }
      this.$get(this.url.list, {
        ...params
      }).then(r => {
        let data = r.data.data;
        const pagination = { ...this.pagination };
        pagination.total = data.total;
        this.dataSource = data.rows;
        this.pagination = pagination;
        // 数据加载完毕，关闭loading
        this.loading = false;
      });
    },
    search() {
      let { sortedInfo, filteredInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      });
    },
    reset() {
      // 取消选中
      this.selectedRowKeys = [];
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent;
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent;
        this.paginationInfo.pageSize = this.pagination.defaultPageSize;
      }
      // 重置列过滤器规则
      this.filteredInfo = null;
      // 重置列排序规则
      this.sortedInfo = null;
      // 重置查询参数
      this.queryParams = {};
      this.fetch();
    },
    handleAdd: function() {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },
    batchDel: function() {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!");
        return;
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一条记录！");
      } else {
        let ids = "";
        for (let a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        const that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function() {
            that.loading = true;
            that
              .$delete(that.url.delete + ids)
              .then(r => {
                if (r.data.success) {
                  that.$message.success("删除成功");
                  that.selectedRowKeys = [];
                  that.search();
                } else {
                  that.$message.warning("删除失败");
                }
              })
              .finally(() => {
                that.loading = false;
              });
          }
        });
      }
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    handleTableChange(pagination) {
      this.paginationInfo = pagination;
      this.fetch({
        ...this.queryParams
      });
    },
    handleEdit: function(record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleDelete: function(id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!");
        return;
      }
      const that = this;
      that.$delete(that.url.delete + id).then(r => {
        if (r.data.success) {
          that.$message.success("删除成功");
          that.search();
        } else {
          that.$message.warning("删除失败");
        }
      });
    },
    modalFormOk() {
      // 重载列表
      this.search();
      //清空列表选中
      this.onClearSelected();
    },
    //执行发布操作
    doPublish: function(id) {
      const that = this;
      let param = { noticeId: id };
      this.$get(this.url.publish, param).then(r => {
        if (r.data.success) {
          that.$message.success(r.data.message);
          that.search();
        } else {
          that.$message.warning(r.data.message);
        }
      });
    },
    //执行撤销操作
    doRevoke: function(id) {
      const that = this;
      let param = { noticeId: id };
      this.$get(this.url.revoke, param).then(r => {
        if (r.data.success) {
          that.$message.success(r.data.message);
          that.search();
          this.syncNotice(id);
        } else {
          that.$message.warning(r.data.message);
        }
      });
    },
    // 执行同步
    syncNotice(noticeId) {
      this.$get("api/notice/sync", { noticeId: noticeId });
    },
    handleDetail: function(record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "详情";
      this.$refs.modalForm.disableSubmit = true;
      this.$refs.modalForm.disabled = true;
    }
  }
};
</script>
<style scoped>
@import "../../../assets/less/common.less";
</style>
